var wgtVer = null;

function plusReady() {

	plus.runtime.getProperty(plus.runtime.appid, function(inf) {
		wgtVer = inf.version.toString();
		//暂停自动更新
		checkUpdate();
	});
}
if(window.plus) {
	plusReady();
} else {
	document.addEventListener('plusready', plusReady, false);
}

function checkUpdate() {
	var url = getServletUrl("LoginServlet");
	$.ajax({
		type: "POST",
		url: url,
		data: {
			commdCode: "getWellVersion"
		},
		dataType: "json",
		success: function(data) {
			var newVer = data;
			if(wgtVer && newVer && (wgtVer != newVer)) {
				var strCon = "现在版本:" + wgtVer + ",服务器版本:" + newVer + "\n是否版本更新？";
				var btnArray = ['取消', '确定'];
				mui.confirm(strCon, '提示', btnArray, function(e) {
					if(e.index == 1) {
						downWgt();
					} else {}
				})
			} else {

			}
		},
		error:function(data){
		}
	});

}

function downWgt() {
	plus.nativeUI.showWaiting("下载更新文件...");
	plus.downloader.createDownload(wgtUrl, {
		filename: "_doc/update/"
	}, function(d, status) {
		if(status == 200) {
			console.log("下载更新成功：" + d.filename);
			installWgt(d.filename); // 安装wgt包
		} else {
			console.log("下载更新失败！");
			plus.nativeUI.alert("下载更新失败！");
		}
		plus.nativeUI.closeWaiting();
	}).start();
}
// 更新应用资源
function installWgt(path) {
	plus.nativeUI.showWaiting("安装更新文件...");
	plus.runtime.install(path, {}, function() {
		plus.nativeUI.closeWaiting();
		console.log("安装更新文件成功！");
		plus.nativeUI.alert("应用资源更新完成！", function() {
			plus.runtime.restart();
		});
	}, function(e) {
		plus.nativeUI.closeWaiting();
		console.log("安装更新文件失败[" + e.code + "]：" + e.message);
		plus.nativeUI.alert("安装更新文件失败[" + e.code + "]：" + e.message);
	});
}